package se.ytterman.jserial.framework.device;

import java.lang.*;
import java.util.*;
import java.util.concurrent.*;

import se.ytterman.jserial.util.BinaryDumpUtil;

import se.ytterman.jserial.io.CommunicationAdapter;

public class DeviceInputThread extends Thread {

    public DeviceInputThread(CommunicationAdapter communicationsAdapter,
                             PriorityBlockingQueue requestQueue) {
	// Set interface reference
	this.communicationsAdapter = communicationsAdapter;
        
        // Set outbound queue reference
	this.requestQueue = requestQueue;
    }

    public void run() {
	// Write forever...
	while(1==1) {
	    try {
                // Fetch first element in queue...
                Request currentRequest = this.requestQueue.take();
                
                // DEBUG BinaryDumpUtil.printCleanString(currentRequest.toByteArray(), System.out);
                
	        // Send command...
                this.communicationsAdapter.write(currentRequest.toByteArray());
                          
                // DEBUG System.out.println(currentRequest.getRequestId());            
            }               
            catch(Exception e) {
                System.out.println("DeviceInputThread.run():" + e.toString());	    
            }
	}
    }

    private CommunicationAdapter communicationsAdapter;
    private PriorityBlockingQueue <Request> requestQueue;
}
